﻿using System;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace GazelDoor.Controlli
{
    public class GazelConnessione : IDisposable
    {
        private static GazelConnessione session;

        public static GazelConnessione Istance()
        {
            if (session == null)
                session = new GazelConnessione();
            return session;
        }

        public SqlConnection Connessione { get; private set; }

        private bool disposed = false;

        private GazelConnessione()
        {
            ApriConnessione();
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    ChiudiConnessione();
                    session = null;
                }
                disposed = true;
            }
        }

        ~GazelConnessione()
        {
            Dispose(false);
        }

        private void ApriConnessione()
        {
            SqlConnectionStringBuilder build = new SqlConnectionStringBuilder();
            build.DataSource = "Carlo-PC";
            build.UserID = "sa";
            build.Password = "esis";
            build.InitialCatalog = "Archivio";
            Connessione = new SqlConnection(build.ConnectionString);
            try
            {
                Connessione.Open();
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Errore in sql" + ex.Message + "\n" + ex.StackTrace);
                return;
            }
        }

        private void ChiudiConnessione()
        {
            try
            {
                Connessione.Close();
            }
            catch (SqlException ex)
            {
                MessageBox.Show("Errore: " + ex.Message + "\n" + ex.StackTrace);
                return;
            }
        }
    }
}